package com.supply.dl.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.supply.dl.R;
import com.supply.dl.app.AppConfig;
import com.supply.dl.app.http.BaseInfo;
import com.supply.dl.bean.BaseItemBean;
import com.supply.dl.bean.BaseMultiItemBean;
import com.supply.dl.bean.EventBusImage;
import com.supply.dl.bean.InAndOutBoundLocationBean;
import com.supply.dl.bean.JobAttachBean;
import com.supply.dl.bean.JobInfoBean;
import com.supply.dl.bean.MaterialInfoBean;
import com.supply.dl.bean.OperateFlagEnum;
import com.supply.dl.bean.PositionInfoBean;
import com.supply.dl.bean.ReceivingAndSendGoodsConfirmDetailBean;
import com.supply.dl.bean.SearchStockBean;
import com.supply.dl.bean.SelectDictionaryBean;
import com.supply.dl.bean.WorkNotesBean;
import com.supply.dl.constant.Constants;
import com.supply.dl.http.HttpManger;
import com.supply.dl.utils.CommonNormalAdapterUtil;
import com.supply.dl.utils.InterfaceUtil;
import com.supply.dl.utils.RecyclerViewUtil;
import com.supply.dl.utils.StringUtils;
import com.supply.dl.utils.Utils;
import com.supply.dl.utils.utils.FileUtils;
import com.supply.dl.utils.utils.ToastUtil;
import com.supply.dl.view.MaxRecyclerView;
import com.supply.dl.widget.LoadTipFailedLayout;
import com.supply.dl.widget.adapter.BaseMultiItemAdapter;
import com.supply.dl.widget.adapter.CommonNormalAdapter;
import com.supply.dl.widget.adapter.ReceivingAndSendGoodsConfirmMultiItemAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ${qianzhihe} on 2018/7/18.
 * 发货确认详情、收货确认详情界面
 */

public class ReceivingAndSendGoodsConfirmDetailActivity extends BaseActivity implements BaseQuickAdapter.OnItemChildClickListener {

    /**
     * 加载框
     */
    @BindView(R.id.receiving_and_send_goods_confirm_detail_main_loadView)
    LoadTipFailedLayout loadTipFailedLayout;

    @BindView(R.id.common_letter_of_notice_info_showNoticeLetterNo)
    TextView showNoticeLetterNo;//通知单号
    @BindView(R.id.common_letter_of_notice_info_positionStatusName)
    TextView positionStatusName;//收货状态
    /**
     * ERP单号
     */
    @BindView(R.id.common_letter_of_notice_info_firstTv)
    TextView tvFirstName;
    @BindView(R.id.common_letter_of_notice_info_showFirstValue)
    TextView showFirstValue;

    /**
     * 司机
     */
    @BindView(R.id.common_letter_of_notice_info_secondTv)
    TextView tvSecondName;
    @BindView(R.id.common_letter_of_notice_info_showSecondValue)
    TextView showSecondValue;

    /**
     * 车牌号
     */
    @BindView(R.id.common_letter_of_notice_info_thirdTv)
    TextView tvThirdName;
    @BindView(R.id.common_letter_of_notice_info_showThirdValue)
    TextView showThirdValue;

    /**
     * 供应商
     */
    @BindView(R.id.common_letter_of_notice_info_fourthTv)
    TextView tvFourth;
    @BindView(R.id.common_letter_of_notice_info_showFourthValue)
    TextView showFourthValue;
    /**
     * 备注
     */
    @BindView(R.id.common_letter_of_notice_info_fivthTv)
    TextView tvFivth;
    @BindView(R.id.common_letter_of_notice_info_showFivthValue)
    TextView showFivthValue;

    @BindView(R.id.receiving_and_send_goods_confirm_detail_main_lyPostingAccount)
    LinearLayout lyPostingAccount;

    /**
     * 物料和作业模块列表
     */
    @BindView(R.id.receiving_and_send_goods_confirm_detail_main_workRecyclerView)
    MaxRecyclerView workRecyclerView;
    ReceivingAndSendGoodsConfirmMultiItemAdapter workAdapter;
    int workAdapterFlag;
    List<BaseMultiItemBean> itemWorkList;

    int activityFlag;
    InAndOutBoundLocationBean inAndOutBoundLocationBean;
    boolean isReceivingGoodsDetailConfirm;

    int currentSelectedWorkIndex = 0;
    boolean isGetUIData = true;
    ArrayList<WorkNotesBean> remarks ;

    @Override
    protected int getLayoutResource() {
        return R.layout.receiving_and_send_goods_confirm_detail_main;
    }

    @Override
    protected void initView() {
        super.initView();
        showLeftBack();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initLoadingView() {
        super.initLoadingView();
        loadTipFailedLayout.setRestartOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (activityFlag == Constants.FLAG_ACTIVITY_RECEIVING_GOODS_UI) {
                    isReceivingGoodsDetailConfirm = true;
                } else if (activityFlag == Constants.FLAG_ACTIVITY_SEND_GOODS_UI) {
                    isReceivingGoodsDetailConfirm = false;
                }
                getReceivingOrSendGoodsConfirmDetailList(isReceivingGoodsDetailConfirm);
            }
        });
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        itemWorkList = new ArrayList<>();
        remarks=new ArrayList<>();
        inAndOutBoundLocationBean = (InAndOutBoundLocationBean) getIntent().getExtras().get("InAndOutBoundLocationBean");
        activityFlag = getIntent().getIntExtra(Constants.FLAG_ACTIVITY_KEY, Constants.FLAG_ACTIVITY_RECEIVING_GOODS_UI);
        tvFirstName.setText(getStringByResId(R.string.ERPNo));
        tvSecondName.setText(getStringByResId(R.string.driver));
        tvThirdName.setText(getStringByResId(R.string.plateNumber));
        tvFourth.setText(getStringByResId(R.string.supplier));
        tvFivth.setText(getStringByResId(R.string.remarks));
        tvFivth.setVisibility(View.VISIBLE);
        showFivthValue.setVisibility(View.VISIBLE);
        if (activityFlag == Constants.FLAG_ACTIVITY_RECEIVING_GOODS_UI) {
            isReceivingGoodsDetailConfirm = true;
            workAdapterFlag = Constants.FLAG_ACTIVITY_RECEIVING_GOODS_DETAAIL_UI;
            setTitleShow(getResourcesString(R.string.take_delivery_confirm));
        } else if (activityFlag == Constants.FLAG_ACTIVITY_SEND_GOODS_UI) {
            isReceivingGoodsDetailConfirm = false;
            workAdapterFlag = Constants.FLAG_ACTIVITY_SEND_GOODS_DETAILA_UI;
            setTitleShow(getResourcesString(R.string.deliver_goods_confirm));
        }
        getReceivingOrSendGoodsConfirmDetailList(isReceivingGoodsDetailConfirm);
    }

    @Override
    protected void initRecyclerView() {
        super.initRecyclerView();
        RecyclerViewUtil.initLinearLayoutVERTICAL(this, workRecyclerView);
        workAdapter = new ReceivingAndSendGoodsConfirmMultiItemAdapter(itemWorkList);
        workAdapter.setAdapterFlag(workAdapterFlag);
//        workAdapter.setOnItemChildClickListener(this);
        workAdapter.bindToRecyclerView(workRecyclerView);
    }

    @Override
    protected void initListener() {
        super.initListener();
        lyPostingAccount.setOnClickListener(this);
        setRightHomeClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishAllActivityExceptAppointed(MainActivity.class);
            }
        });

        setRightScanClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.startScanActivity(ReceivingAndSendGoodsConfirmDetailActivity.this);
            }
        });
    }

    /**
     * 获取收货确认详情、发货确认详情数据
     *
     * @param isReceivingGoodsConfirmDetail
     */
    private void getReceivingOrSendGoodsConfirmDetailList(boolean isReceivingGoodsConfirmDetail) {
        loadTipFailedLayout.setLoadText(R.string.since_help_loading);
        loadTipFailedLayout.setState(LoadTipFailedLayout.STATE_PROGRESS);
        HttpManger httpManger = HttpManger.getInstance();
        httpManger.setContext(this);
        if (isReceivingGoodsConfirmDetail) {
            httpManger.getReceivingGoodsConfirmDetailList(inAndOutBoundLocationBean.noticeOrderId);
        } else {
            httpManger.getSendGoodsConfirmDetailList(inAndOutBoundLocationBean.noticeOrderId);
        }
        httpManger.setHttpResponseCallBackListener(this);
    }

    @Override
    public void onSuccess(BaseInfo<?> baseInfo) {
        super.onSuccess(baseInfo);
        if (isGetUIData) {
            ReceivingAndSendGoodsConfirmDetailBean confirmDetailBean = (ReceivingAndSendGoodsConfirmDetailBean) baseInfo.getData();
            if (confirmDetailBean != null) {
                loadTipFailedLayout.setState(LoadTipFailedLayout.STATE_FINISH);
                showNoticeLetterNo.setText(confirmDetailBean.noticeOrderNo);
                positionStatusName.setText(confirmDetailBean.displayNodOrderStatusName);

                showFirstValue.setText(inAndOutBoundLocationBean.erpOrderNo);
                showSecondValue.setText(confirmDetailBean.driverName);
                showThirdValue.setText(confirmDetailBean.carNo);
                showFourthValue.setText(confirmDetailBean.saleDealerName);
                showFivthValue.setText(confirmDetailBean.remark);
                ArrayList<MaterialInfoBean> materialInfoBeanList = confirmDetailBean.getNoticeOrderDetailList();
                itemWorkList.clear();
                if (materialInfoBeanList != null && materialInfoBeanList.size() > 0) {
                    int i=-1;
                    for (MaterialInfoBean materialInfoBean : materialInfoBeanList) {
                        ++i;
                        materialInfoBean.mPosition=i;
                        itemWorkList.add(new BaseMultiItemBean(materialInfoBean, Constants.FLAG_RECEIVING_AND_SEND_GOODS_DETAAIL_UI_MATERIEL_ITEM));
                        ArrayList<JobInfoBean> jobList = materialInfoBean.getJobInfoList();
                        int j=-1;
                        if (jobList != null && jobList.size() > 0) {
                            for (JobInfoBean jobInfoBean : jobList) {
                                ++j;
                                jobInfoBean.mPosition=j;
                                itemWorkList.add(new BaseMultiItemBean(jobInfoBean, Constants.FLAG_RECEIVING_AND_SEND_GOODS_DETAILA_UI_WORK_ITEM));
                            }
                        }
                    }
                }
                workAdapter.setNewData(itemWorkList);
            } else {
                loadTipFailedLayout.setTextColor(R.color.color_gray);
                loadTipFailedLayout.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
                loadTipFailedLayout.setNormalText(R.string.noMessage);
                loadTipFailedLayout.setState(LoadTipFailedLayout.STATE_NORMAL);
            }
        } else {
            ToastUtil.showToast(ReceivingAndSendGoodsConfirmDetailActivity.this, baseInfo.getMessage());
            if (baseInfo.isHandleState()){
                finish();
            }
        }
    }

    @Override
    public void onFailure(String message) {
        super.onFailure(message);
        loadTipFailedLayout.setTextColor(R.color.color_gray);
        loadTipFailedLayout.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
        loadTipFailedLayout.setNormalText(R.string.since_help_load_failed);
        loadTipFailedLayout.setState(LoadTipFailedLayout.STATE_FAILED);
        ToastUtil.showToast(ReceivingAndSendGoodsConfirmDetailActivity.this, message);
    }

    @OnClick({R.id.receiving_and_send_goods_confirm_detail_main_tvPostingAccount})
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.receiving_and_send_goods_confirm_detail_main_tvPostingAccount://过账
                isGetUIData=false;
                HttpManger httpManger = HttpManger.getInstance();
                httpManger.setContext(this);
                if (activityFlag == Constants.FLAG_ACTIVITY_RECEIVING_GOODS_UI) {
                    isReceivingGoodsDetailConfirm = true;
                    httpManger.receivingGoodsConfirmDetailPostingAccount(inAndOutBoundLocationBean.noticeOrderId);
                } else if (activityFlag == Constants.FLAG_ACTIVITY_SEND_GOODS_UI) {
                    isReceivingGoodsDetailConfirm = false;
                    httpManger.sendGoodsConfirmDetailPostingAccount(inAndOutBoundLocationBean.noticeOrderId);
                }
                httpManger.setHttpResponseCallBackListener(this);
                break;
        }
    }

    /**
     * 作业列表
     * 删除点击事件
     * 确认作业点击事件
     * item点击事件
     * @param adapter
     * @param view
     * @param position
     */
    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        currentSelectedWorkIndex = position;
        workItemClick(position, view);
    }

    /**
     * 作业列表item上点击事件
     *
     * @param currentSelectedLocationPosition 当前定位列表点击item的position
     * @param view
     */
    private void workItemClick(int currentSelectedLocationPosition, View view) {
        int reqCode = -1;
        Intent intent=null;
        switch (view.getId()) {
            case R.id.work_info_item_showStorehouseTv://仓库
                String action = "";
                intent = new Intent(this, SelectBaseDataActivity.class);
                //0：入库；1：出库
                if (activityFlag == Constants.FLAG_ACTIVITY_RECEIVING_GOODS_UI) {
                    action = AppConfig.BaseDataAction.WARE_HOUSE_TYPE_0;
                    reqCode = AppConfig.BaseDataAction.REQCODE_NOTICE_IN_BOUND_DETAIL;
                } else {
                    action = AppConfig.BaseDataAction.WARE_HOUSE_TYPE_1;
                    reqCode = AppConfig.BaseDataAction.REQCODE_NOTICE_OUT_BOUND_DETAIL;
                }
                intent.putExtra("action", action);
                startActivityForResult(intent, reqCode);
                break;
            case R.id.work_info_item_showReservoirPositionTv://库位
                intent= new Intent(this, DepotSelectActivity.class);
                if (activityFlag==Constants.FLAG_ACTIVITY_RECEIVING_GOODS_UI){
                    reqCode = AppConfig.BaseDataAction.REQCODE_NOTICE_IN_BOUND_DETAIL_BY_DEPOT;
                }else {
                    reqCode = AppConfig.BaseDataAction.REQCODE_NOTICE_OUT_BOUND_DETAIL_BY_DEPOT;
                }
                startActivityForResult(intent, reqCode);
                break;
            case R.id.work_info_item_sureWorkBtn://确认作业
                break;
            case R.id.work_info_item_showJobRecordTv://作业记录
                intent = new Intent(this, OperateRemarkActivity.class);
                startActivityForResult(intent, AppConfig.BaseDataAction.REQCODE_JOB_RECORD);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode==HEAD_ABLUME | requestCode==HEAD_CAREAM){
            switch (requestCode){
                case HEAD_ABLUME://相册返回
                    // 判断手机版本，因为在4.4版本都手机处理图片返回的方法就不一样了
                    //4.4以后返回的不是真实的uti而是一个封装过后的uri 所以要对封装过后的uri进行解析
                    if (data!=null){
                        if (Build.VERSION.SDK_INT >= 19) {
                            //4.4系统一上用该方法解析返回图片
                            displayImage(handleImageOnKitKat(data));
                        } else {
                            //4.4一下用该方法解析图片的获取
                            displayImage(handleImageBeforeKitKat(data));
                        }
                    }
                    break;
                case HEAD_CAREAM://相机
                    if (data!=null){
                        Bundle bundle=data.getExtras();
                        if (bundle!=null){//照相后，点击取消时，该bundle为空
                            Bitmap bitmap= (Bitmap) bundle.get("data");
                            String fileName= FileUtils.saveImage(bitmap);//保存照相的图片
                            Uri uri=Uri.fromFile(FileUtils.getFile(fileName));
                            displayImage(FileUtils.getRealFilePathToUri(ReceivingAndSendGoodsConfirmDetailActivity.this, uri));
                        }
                    }
                    break;
            }
            return;
        }

        JobInfoBean jobInfoBean = (JobInfoBean) itemWorkList.get(currentSelectedWorkIndex).object;
        /**
         * 获取作业记录数据
         */
        if (data != null && requestCode == AppConfig.BaseDataAction.REQCODE_JOB_RECORD) {
            remarks = (ArrayList<WorkNotesBean>) data.getSerializableExtra("remarks");
            if (remarks.size() > 0) {
                String workNoteName = "";
                for (int i = 0; i < remarks.size(); i++) {
                    if (StringUtils.isBlank(workNoteName))
                        workNoteName = remarks.get(i).getDepart();
                    else
                        workNoteName = workNoteName + "," + remarks.get(i).getDepart();
                }
                jobInfoBean.jobRecord=workNoteName;
                workAdapter.notifyItemChanged(currentSelectedWorkIndex);
            }
            return;
        }

        if (data == null || data.getSerializableExtra("selectBean") == null)
            return;

        switch (requestCode){
            case AppConfig.BaseDataAction.REQCODE_NOTICE_IN_BOUND_DETAIL:
            case AppConfig.BaseDataAction.REQCODE_NOTICE_OUT_BOUND_DETAIL:
                SelectDictionaryBean selectBean = (SelectDictionaryBean) data.getSerializableExtra("selectBean");
                jobInfoBean.whName = selectBean.getText();
                workAdapter.notifyItemChanged(currentSelectedWorkIndex);
                break;
            case AppConfig.BaseDataAction.REQCODE_NOTICE_IN_BOUND_DETAIL_BY_DEPOT:
            case AppConfig.BaseDataAction.REQCODE_NOTICE_OUT_BOUND_DETAIL_BY_DEPOT:
                SearchStockBean searchStockBean= (SearchStockBean) data.getSerializableExtra("selectBean");
                jobInfoBean.stockName = searchStockBean.getStockName();
                workAdapter.notifyItemChanged(currentSelectedWorkIndex);
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(final EventBusImage eventBusImage){
        currentSelectedWorkIndex=eventBusImage.currentItemPosition;
        openAblumeOrCaream(eventBusImage.flag);
    }

    /**
     * 打开相册或者相机
     * @param flag
     */
    private void openAblumeOrCaream(int flag){
        switch (flag){
            case HEAD_ABLUME://相册
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent, HEAD_ABLUME);
                break;
            case HEAD_CAREAM://相机
                Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(camera, HEAD_CAREAM);
                break;
        }
    }

    /**
     * 通过imagepath来绘制immageview图像
     *
     * @param imagPath
     */
    protected void displayImage(String imagPath) {
        if (imagPath != null) {
//            Bitmap bitmap = BitmapFactory.decodeFile(imagPath);
//            bean.setBitmap(bitmap);
            JobAttachBean jobAttachBean=new JobAttachBean();
            jobAttachBean.attachUrl=imagPath;
            ArrayList<JobAttachBean> imageList=new ArrayList<>();
            imageList.add(jobAttachBean);
            JobInfoBean jobInfoBean = (JobInfoBean) itemWorkList.get(currentSelectedWorkIndex).object;
            jobInfoBean.setJobAttachList(imageList);
            jobInfoBean.imagePath=imagPath;
            workAdapter.notifyItemChanged(currentSelectedWorkIndex);
        } else {
            ToastUtil.showToast(this, "图片获取失败");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
